<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" style="margin-bottom:30px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['drug:drug:add']"
        >新增药品</el-button>
      </el-col>  
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['drug:drug:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="处方类别" prop="drugInformationId">
        <el-select v-model="queryParams.drugInformationId" placeholder="处方类别" clearable style="width: 100px">
          <el-option
            v-for="dict in informationList"
            :key="dict.id"
            :label="dict.drugInformationName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="药品状态" prop="drugStatus">
        <el-select v-model="queryParams.drugStatus" placeholder="药品状态" clearable style="width: 100px">
          <!-- 下拉框选择停用和启用 -->
          <el-option label="全部" value='' />
          <el-option label="停用" value='停用' />
          <el-option label="启用" value='启用' />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreationTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="药品编码" prop="drugCode">
        <el-input
          v-model="queryParams.drugCode"
          placeholder="请输入药品编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="药品名称" prop="drugGenericName">
        <el-input
          v-model="queryParams.drugGenericName"
          placeholder="请输入药品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产厂家" prop="drugManufacturer">
        <el-select v-model="queryParams.drugManufacturer" placeholder="请选择生产厂家" clearable style="width: 200px">
          <el-option
            v-for="dict in doctor_drug_manufacturer"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

   

    <el-table v-loading="loading" :data="drugList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="药品编码" align="center" prop="drugCode" />
      <el-table-column label="药品名称" align="center" prop="drugGenericName" />
      <el-table-column label="规格" align="center" prop="drugSpecification" />
      <el-table-column label="收费类别" align="center" prop="drugInformationId">
        <template #default="scope">
           {{informationList.find(item => item.id == scope.row.drugInformationId)?.drugInformationName || '未知' }}
        </template>
      </el-table-column>  
      <el-table-column label="采购价" align="center" prop="purchasePrice" />
      <el-table-column label="零售价" align="center" prop="retailPrice" />
      <el-table-column label="生产厂家" align="center" prop="drugManufacturer">
        <template #default="scope">
          <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.drugManufacturer"/>
        </template>
      </el-table-column>
      <el-table-column label="药品状态" align="center" prop="drugStatus">
        <template #default="scope">
          <!-- <dict-tag :options="sys_common_status" :value="scope.row.drugStatus"/> -->
          <el-tag v-if="scope.row.drugStatus == '启用'" type="success">启用</el-tag>
          <el-tag v-if="scope.row.drugStatus == '停用'" type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="creationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drug:drug:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="blockUp(scope.row)" v-hasPermi="['drug:drug:edit']" v-if="scope.row.drugStatus == '启用'" >停用</el-button>
          <el-button link type="primary" icon="Delete" @click="blockUp(scope.row)" v-hasPermi="['drug:drug:edit']" v-if="scope.row.drugStatus == '停用'" >启用</el-button>
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['drug:drug:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品信息对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="drugRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="药品信息分类" prop="drugInformationId" label-width="120px">
          <el-radio-group v-model="form.drugInformationId">
            <el-radio
              v-for="dict in informationList"
              :key="dict.drugInformationId"
              :label="dict.id"
            >{{dict.drugInformationName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <h2>基本信息</h2>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="药品编码" prop="drugCode">
              <el-input v-model="form.drugCode" placeholder="请输入药品编码" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品条形码" prop="drugBarcode">
              <el-input v-model="form.drugBarcode" placeholder="请输入药品条形码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品通用名" prop="drugGenericName">
              <el-input v-model="form.drugGenericName" placeholder="请输入药品通用名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="拼音码" prop="pinyinCode">
              <el-input v-model="form.pinyinCode" placeholder="请输入拼音码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="药品分类" prop="drugCategory">
              <el-select v-model="form.drugCategory" placeholder="请选择药品分类">
                <el-option
                  v-for="dict in doctor_drug_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品规格" prop="drugSpecification">
              <el-input v-model="form.drugSpecification" placeholder="请输入药品规格" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品剂型" prop="drugForm">
              <el-select v-model="form.drugForm" placeholder="请选择药品剂型">
                <el-option
                  v-for="dict in doctor_drug_form"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="OTC药品" prop="otcFlag">
              <el-radio-group v-model="form.otcFlag">
                <el-redio>
                  <el-radio :label="'是'">是</el-radio>
                  <el-radio :label="'否'">否</el-radio>
                </el-redio>
              </el-radio-group>
            </el-form-item>
          </el-col>        
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="发票项目" prop="invoiceItem">
              <el-select v-model="form.invoiceItem" placeholder="请选择发票项目">
                <el-option
                  v-for="dict in doctor_invoice_item"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批准文号" prop="approvalNumber">
              <el-input v-model="form.approvalNumber" placeholder="请输入批准文号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产厂家" prop="drugManufacturer">
              <el-select v-model="form.drugManufacturer" placeholder="请选择生产厂家">
                <el-option
                  v-for="dict in doctor_drug_manufacturer"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品状态" prop="drugStatus">
              <el-radio-group v-model="form.drugStatus">
                <!-- <el-radio
                  v-for="dict in sys_common_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio> -->
                <el-radio :label="'停用'">停用</el-radio>
                <el-radio :label="'启用'">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <h2>包装信息</h2>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="包装单位" prop="packagingUnit">
              <el-select v-model="form.packagingUnit" placeholder="请选择包装单位">
                <el-option
                  v-for="dict in doctor_packaging_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" >
            <el-form-item label="基本单位 " prop="basicUnit">
              <el-select v-model="form.basicUnit" placeholder="请选择基本单位 ">
                <el-option
                  v-for="dict in doctor_packaging_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="基本单位 " prop="basicUnit">
              <el-select v-model="form.basicUnit" placeholder="请选择基本单位 ">
                <el-option
                  v-for="dict in doctor_packaging_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" >
            <el-form-item label="剂量系数" prop="doseCoefficient">
              <el-input v-model="form.doseCoefficient" placeholder="请输入剂量系数" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" >
          <el-col :span="6" >
            <el-form-item label="剂量单位" prop="coefficienUnit" >
              <el-select v-model="form.coefficienUnit" placeholder="请选择剂量单位">
                <el-option
                  v-for="dict in doctor_packaging_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购价" prop="purchasePrice">
              <el-input v-model="form.purchasePrice" placeholder="请输入采购价" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="零售价" prop="retailPrice">
              <el-input v-model="form.retailPrice" placeholder="请输入零售价" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="允许拆零" prop="allowBreakage">
              <el-radio-group v-model="form.allowBreakage">
                <!-- <el-radio
                  v-for="dict in sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio> -->
                <el-radio :label="'是'">是</el-radio>
                <el-radio :label="'否'">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="允许会员折扣" prop="allowMemberDiscount">
          <el-radio-group v-model="form.allowMemberDiscount">
            <el-radio :label="'是'">是</el-radio>
            <el-radio :label="'否'">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <h2>功能说明</h2>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="药品用法" prop="drugUsage">
              <el-select v-model="form.drugUsage" placeholder="请选择药品用法">
                <el-option
                  v-for="dict in doctor_drug_usage"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单次用量" prop="singleDose">
              <el-input v-model="form.singleDose" placeholder="请输入单次用量" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="频度" prop="frequency">
              <el-select v-model="form.frequency" placeholder="请选择频度">
                <el-option label="一天1次" value='一天1次' />
                <el-option label="一天2次" value='一天2次' />
                <el-option label="一天3次" value='一天3次' />
                <el-option label="一天4次" value='一天4次' />
                <el-option label="2小时1次" value='2小时1次' />
                <el-option label="4小时1次" value='4小时1次' />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6"></el-col>
        </el-row>
        
        <h2>其他信息 </h2>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="库存下限" prop="inventoryLowerLimit">
              <el-input v-model="form.inventoryLowerLimit" placeholder="请输入库存下限" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="库存上限" prop="inventoryUpperLimit">
              <el-input v-model="form.inventoryUpperLimit" placeholder="请输入库存上限" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货位号" prop="locationCode">
              <el-input v-model="form.locationCode" placeholder="请输入货位号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货位号" prop="locationCode">
              <el-input v-model="form.locationCode" placeholder="请输入货位号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
           <!-- <el-form-item label="创建时间" prop="creationTime">
                    <el-date-picker clearable
                      v-model="form.creationTime"
                      type="date"
                      value-format="YYYY-MM-DD"
                      placeholder="请选择创建时间">
                    </el-date-picker>
                  </el-form-item> -->
          <el-col :span="6">
             <el-form-item label="有效期预警" prop="expiryWarning">
                <el-date-picker clearable
                  v-model="form.expiryWarning"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择有效期时间">
                </el-date-picker>
              </el-form-item>

            <!-- <el-form-item label="有效期预警" prop="expiryWarning">
              <el-input v-model="form.expiryWarning" placeholder="请输入有效期预警" />
            </el-form-item> -->
          </el-col>
          <el-col :span="6">
            <el-form-item label="药品说明" prop="drugDescription">
              <el-input v-model="form.drugDescription" placeholder="请输入药品说明" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="6"></el-col>
        </el-row>
       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Drug">
import { listDrug, getDrug, delDrug, addDrug, updateDrug,getDrugCode } from "@/api/drug/drug";
import { listInformation } from "@/api/drug/information";


const { proxy } = getCurrentInstance();
const { doctor_packaging_unit, doctor_drug_manufacturer, doctor_drug_form, sys_common_status, sys_yes_no, doctor_drug_category, doctor_invoice_item, doctor_drug_usage } = proxy.useDict('doctor_packaging_unit', 'doctor_drug_manufacturer', 'doctor_drug_form', 'sys_common_status', 'sys_yes_no', 'doctor_drug_category', 'doctor_invoice_item', 'doctor_drug_usage');

const drugList = ref([]);
const informationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreationTime = ref([]);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    drugInformationId: null,
    drugCode: null,
    drugGenericName: null,
    drugManufacturer: null,
    drugStatus: null,
    creationTime: null,
    drugInventory:null
  },
  rules: {
    drugInformationId: [{ required: true, message: "处方类别不能为空", trigger: "change" }],
    drugCode: [{ required: true, message: "药品编码不能为空", trigger: "blur" }],
    drugGenericName: [{ required: true, message: "药品通用名不能为空", trigger: "blur" }],
    drugCategory: [{ required: true, message: "药品分类不能为空", trigger: "change" }],
    drugSpecification: [{ required: true, message: "药品规格不能为空", trigger: "blur" }],
    invoiceItem: [{ required: true, message: "发票项目不能为空", trigger: "change" }],
    drugManufacturer: [{ required: true, message: "生产厂家不能为空", trigger: "change" }],
    purchasePrice: [{ required: true, message: "采购价不能为空", trigger: "blur" }],
    retailPrice: [{ required: true, message: "零售价不能为空", trigger: "blur" }],
    drugStatus: [{ required: true, message: "药品状态不能为空", trigger: "change" }],
    otcFlag: [{ required: true, message: "OTC药品必须选择", trigger: "change" }],
    packagingUnit: [{ required: true, message: "包装单位不能为空", trigger: "change" }],
    drugUsage: [{ required: true, message: "药品用法不能为空", trigger: "change" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询药品信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreationTime && '' != daterangeCreationTime) {
    queryParams.value.params["beginCreationTime"] = daterangeCreationTime.value[0];
    queryParams.value.params["endCreationTime"] = daterangeCreationTime.value[1];
  }
  listDrug(queryParams.value).then(response => {
    drugList.value = response.rows;
    console.log(drugList.value);
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询药品信息分类列表 */
function getlistInformationList() {
  loading.value = true;
  listInformation(queryParams.value).then(response => {
    informationList.value = response.rows;
    // console.log(informationList.value);
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    drugInformationId: null,
    drugCode: null,
    drugBarcode: null,
    drugGenericName: null,
    pinyinCode: null,
    drugCategory: null,
    drugSpecification: null,
    drugForm: null,
    otcFlag: null,
    invoiceItem: null,
    approvalNumber: null,
    drugManufacturer: null,
    drugStatus: null,
    packagingUnit: null,
    basicCoefficient: null,
    basicUnit: null,
    doseCoefficient: null,
    coefficienUnit: null,
    purchasePrice: null,
    retailPrice: null,
    allowBreakage: null,
    allowMemberDiscount: null,
    drugUsage: null,
    singleDose: null,
    frequency: null,
    inventoryLowerLimit: null,
    inventoryUpperLimit: null,
    locationCode: null,
    expiryWarning: null,
    drugDescription: null,
    remarks: null,
    del: null,
    creationTime: null
  };
  proxy.resetForm("drugRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreationTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加药品信息";
  getDrugCode().then(response => {
    form.value.drugCode = response.data;
  });

}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDrug(_id).then(response => {
    form.value = response.data;
  
    open.value = true;
    title.value = "修改药品信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["drugRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDrug(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDrug(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 停用按钮
function blockUp(row) {
  // 将当前数据的状态改成停用
  form.value = row
  // 提示
  if(form.value.drugStatus=='启用'){
        form.value.drugStatus='停用'
        updateDrug(form.value).then(response => {
          proxy.$modal.msgSuccess("停用成功");
          open.value = false;
          getList();
        });
      }else{
        form.value.drugStatus='启用'
        updateDrug(form.value).then(response => {
          proxy.$modal.msgSuccess("启用成功");
          open.value = false;
          getList();
        });
      }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品信息编号为"' + _ids + '"的数据项？').then(function() {
    return delDrug(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('drug/drug/export', {
    ...queryParams.value
  }, `drug_${new Date().getTime()}.xlsx`)
}

getList();
getlistInformationList();
</script>
